<template>
	<view>
		<view v-if="$validatenull(deviceData)">
			<cust-empty desc="暂无车辆,请前往绑定!" btnText="前往绑定" :showDefaultBtn="true"
				@clickBtn="$navigateTo('/pagesMy/views/addDevice')">
			</cust-empty>
		</view>
		<view class="p30" v-else>
			<!-- 车辆数据 -->
			<view class="flex-between">
				<view class="flex-align-center">
					<text class="f36 bold mr20">{{deviceData.nickName}}</text>
					<u-icon name="bianji" color="#AAB1C2" size="14" :isShowIcon="false"
						customPrefix="iconfontbike iconbike" @click="editBikeName"></u-icon>
				</view>
			</view>
		<!-- 	<view class="flex-row mt10 f20">
				<view class="bg-white ptb6lr10">
					累计启动<text class="bold plr6 c-primary2">{{$value(statisticsData.carStartCount,-1,0)}}</text>次
				</view>
				<view class="bg-white ptb6lr10 ml20">
					累计故障<text class="bold plr6 c-danger">{{$value(statisticsData.carFaultCount,-1,0)}}</text>次
				</view>
				<view class="bg-white ptb6lr10 ml20 ">
					围栏启用<text class="bold plr6">{{$value(statisticsData.carEnclosureStartCount,-1,0)}}</text>次
				</view>
			</view> -->
			<view class="mt30 flex-between flex-align-center">
				<view class="f20">
					<view class="flex-align-center">
						<u-icon name="chejiahao" color="#0088FF" :isShowIcon="false"
							customPrefix="iconfontbike iconbike">
						</u-icon>
						<text class="ml4 c-desc">车架号码：</text>
						<text>{{deviceData.vin}}</text>
					</view>
					<view class="flex-align-center mt30">
						<u-icon name="xinxinicon" color="#0EE306" size="16" :isShowIcon="false"
							customPrefix="iconfontbike iconbike"></u-icon>
						<view style="position: relative;left: -10px;">
							<text class="c-desc">发动机号：</text>
							<text>{{deviceData.engineNum}}</text>
						</view>
					</view>
					<view class="flex-align-center mt30">
						<u-icon name="chepai1" color="#F0B104" :isShowIcon="false" customPrefix="iconfontbike iconbike">
						</u-icon>
						<text class="deviceData c-desc">车牌号码：</text>
						<text class="mr10">{{deviceData.licensePlateNumber}}</text>
						<u-icon name="bianji" color="#AAB1C2" size="14" :isShowIcon="false"
							customPrefix="iconfontbike iconbike" @click="editBikeNumber"></u-icon>
					</view>
					<view class="flex-align-center mt30">
						<u-icon name="riqi" color="#0099CC" size="16" :isShowIcon="false"
							customPrefix="iconfontbike iconbike"></u-icon>
						<text class="ml4 c-desc">注册日期：</text>
						<text>{{$value(deviceData.authTime) != "-" ? deviceData.authTime.split(" ")[0] : "-"}}</text>
					</view>
				</view>
				<view>
					<image :src="deviceData.carPhotoLink ? deviceData.carPhotoLink  : '/static/images/index/bike.png'"
						style="width:150px;" mode="widthFix"></image>
				</view>
			</view>

			<!-- 卡片数据  width 百分数无效-->
			<view class="flex-row mt40">
				<view class="card-shadow-box p20 flex-column-center wper50">
					<view class="bold flex-row baseline">
						<view class="f48 mr10 dinbold">
							<text  v-if="parseInt(detailDataPoint.surplusOil)<=12" class="flex-center-center">
								<text style="position: relative;top:0upx;font-family: auto;">{{lt}}</text><text class="dinbold">30</text>
							</text>
							<text v-else>
								{{setNumerRound(enduranceMileage, [10, 450], 0)}}
							</text>
						</view>
						<text class="f20">km</text>
					</view>
					<view class="c-info f20 mt10">可续航里程</view>
				</view>
				<view class="card-shadow-box p20 flex-column-center wper50 ml30">
					<view class="bold flex-row baseline">
						<view class="f48 mr10 dinbold">
							<text
								v-if="parseInt(detailDataPoint.surplusOil)<=12">
								油量低
							</text>
							<text v-else>
								{{toFormatVal(detailDataPoint.surplusOil, [0, 100], 0)}}
								<text class="f20">%</text>
							</text>
						
						</view>
						
					</view>
					<view class="c-info f20 mt10">剩余油量</view>
				</view>
			</view>
			<view class="flex-row mt30">
				<view class="card-shadow-box p20 flex-column-center wper50">
					<view class="bold flex-row baseline">
						<view class="f48 mr10 dinbold">
							{{toFormatVal(detailDataPoint.carFrontTirePressure, [0, 3.5], 1)}}
						</view>
						<view class="f20">bar</view>
					</view>
					<view class="c-info f20 mt10">前轮胎压（FR）</view>
				</view>
				<view class="card-shadow-box p20 flex-column-center wper50 ml30">
					<view class="bold flex-row baseline">
						<view class="f48 mr10 dinbold">{{toFormatVal(detailDataPoint.carRearTirePressure, [0, 3.5], 1)}}
						</view>
						<view class="f20">bar</view>
					</view>
					<view class="c-info f20 mt10">后轮胎压（RR）</view>
				</view>
			</view>
			<view class="card-cell-box mt40">
				<u-cell icon="youliang" title="平均油耗" :isLink="true" :iconStyle="{'color':'#57BEB1'}"
					rightIcon="arrow-right" @click="gotoFun('/pagesHome/views/paramsDataOil?title=平均油耗')"><template
						v-slot:value>
						<view class="f24 dinbold "><span
								class="mr4">{{toFormatVal(detailDataPoint.averageOil, [0, 4.5], 1)}}</span><span>L/100km</span>
						</view>
					</template></u-cell>
				<u-cell iconColor="#FEBF4C" icon="dianya" title="电瓶电压" :isLink="true" rightIcon="arrow-right"
					:iconStyle="{'color':'#0EE306'}" @click="gotoFun('/pagesHome/views/paramsData?title=电瓶电压')">
					<template v-slot:value>
						<view class="f24 dinbold "><span
								class="mr4">{{toFormatVal(detailDataPoint.insideVoltage, [6, 16], 1)}}</span><span>V</span>
						</view>
					</template>
				</u-cell>
				<u-cell icon="lichengbiao" title="仪表里程" :isLink="true" rightIcon="arrow-right"
					:iconStyle="{'color':'#0088FF'}" @click="gotoFun('/pagesDetail/views/odometer')">
					<template v-slot:value>
						<view class="f24 dinbold "><span
								class="mr4">{{toFormatVal(detailDataPoint.meterMileage, [0, 999999], 1)}}</span><span>km</span>
						</view>
					</template>
				</u-cell>
				<u-cell icon="qihangjilu" title="骑行记录" :isLink="true" rightIcon="arrow-right"
					:iconStyle="{'color':'#1296DB'}" @click="gotoFun('/pagesHome/views/trackList')"></u-cell>

				<u-cell :border="false" icon="zhenduanxinxi" title="车辆诊断" :isLink="true" rightIcon="arrow-right"
					:iconStyle="{'color':'#1296DB'}" @click="gotoFun('/pagesDetail/views/diagnoseInfoBefore')">
				</u-cell>
			</view>

			<u-modal :show="show" :title="'编辑'+label" :showCancelButton="true" @cancel="cancel" @confirm="confirm">
				<u--input :placeholder="'请输入'+label" v-model="name">

				</u--input>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import {
		editCarAPI,
		verifyCarAPI,
		getCardatastatisticsAPI
	} from "@/api/api/car.js"
	import custEmpty from "@/components/cust-empty/index.vue";
	import dotStatus from "@/components/simple/dot-status";
	import {
		getRangeVal,
		throttle,
		getDifferenceDay
	} from "@/utils/utils.js";
	import {
		mapState
	} from 'vuex'

	import {
		getStoreSyncUtil
	} from "@/utils/store.js"

	export default {
		data() {
			return {
				name: "",
				show: false,
				label: "车辆名称",
				statisticsData: {
					carEnclosureStartCount: 0,
					carFaultCount: 0,
					carStartCount: 0
				},
				isHasModal: false,
				lt:'<'
			}
		},
		components: {
			dotStatus,
			custEmpty
		},
		computed: {
			...mapState(["unReadNum", "deviceData", "detailDataPoint", "enduranceMileage","isProduct"])
		},
		onShow() {
			if(this.isProduct){
				this.gotoAuthDialog();
			}
			this.gotoSubscribeDialog();
			this.$store.commit("setSpecialAppOnShow", false);
			// if (!this.$validatenull(this.deviceData)) {
			// 	getCardatastatisticsAPI(this.deviceData.id).then(([err, data]) => {
			// 		if (err) return;
			// 		if (typeof data != "string") {
			// 			this.statisticsData = {
			// 				carEnclosureStartCount: data.carEnclosureStartCount,
			// 				carFaultCount: data.carFaultCount,
			// 				carStartCount: data.carStartCount
			// 			}
			// 		}

			// 	})
			// }
			if (this.unReadNum == 0) {
				uni.removeTabBarBadge({
					index: 3,
				})
			} else {
				uni.setTabBarBadge({
					index: 3,
					text: this.unReadNum + ''
				})
			}
		},
		watch: {
			"unReadNum": {
				handler(unReadNum) {
					if (this.unReadNum == 0) {
						uni.removeTabBarBadge({
							index: 3,
						})
					} else {
						uni.setTabBarBadge({
							index: 3,
							text: this.unReadNum + ''
						})
					}
				}
			}
		},
		methods: {
			gotoAuthDialog() {
				if (this.deviceData.isAuth == "1" && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					uni.showModal({
						title: '提示',
						content: "当前车辆未认证,如已认证,请5分钟后重新进入小程序",
						showCancel: true,
						cancelText: "退出",
						confirmText: "去认证",
						success(res) {
							if (res.confirm) {
								that.isHasModal = false;
								that.$navigateTo("/pagesMy/views/myMotorbike");
							} else if (res.cancel) {
								that.isHasModal = false;									wx.exitMiniProgram({
										success(res) {
											console.log(JSON.stringify(res));
										},
										fail(res) {
											console.log(
												`exitMiniProgram fail: ${JSON.stringify(res)}`);
										}
									});
							}
						}
					});
				}
			},
			gotoSubscribeDialog() {
				if (!this.$validatenull(this.deviceData.tboxExpireTime) && !this.isHasModal) {
					let that = this;
					this.isHasModal = true;
					let differenceDay = getDifferenceDay(this.deviceData.tboxExpireTime);
					if (differenceDay < 0) {
						uni.showModal({
							title: '提示',
							content: "当前服务已到期，请前往-我的-服务订阅进行订阅",
							showCancel: true,
							cancelText: "退出",
							confirmText: "去订阅",
							success(res) {
								if (res.confirm) {
									that.isHasModal = false;
									that.$switchTab("/pages/views/home/userConfig");
								} else if (res.cancel) {
									that.isHasModal = false;
									wx.exitMiniProgram({
										success(res) {
											console.log(JSON.stringify(res));
										},
										fail(res) {
											console.log(`exitMiniProgram fail: ${JSON.stringify(res)}`);
										}
									});
								}
							}
						});
					}
				}
			},
			$switchTab(url) {
				uni.switchTab({
					url: url
				});
			},
			gotoFun: throttle(function(url) {
				console.log(url);
				this.$navigateTo(url);
			}),
			editBikeNumber: throttle(function() {
				this.editBike('车牌号码')
			}),
			editBikeName: throttle(function() {
				this.editBike('车辆名称')
			}),
			editBike(label) {
				this.label = label;
				this.show = true;
				if (label == "车辆名称") {
					this.name = this.deviceData.nickName;
				} else {
					this.name = this.deviceData.licensePlateNumber;
				}

			},
			cancel() {
				this.show = false;
			},
			confirm() {
				let params = {
					id: this.deviceData.id,
				};
				if (this.label == "车辆名称") {
					params.nickName = this.name;
				} else {
					let licensePlateNumber = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-Z0-9]{5,6}$/;
					if (!this.$validatenull(this.name) && !licensePlateNumber.test(this.name)) {
						this.$showToast("请输入正确的车牌号");
						return;
					}
					params.licensePlateNumber = this.name;
				}
				editCarAPI(params).then(([err, data]) => {
					if (err) return;
					if (this.label == "车辆名称") {
						this.deviceData.nickName = this.name;
					} else {
						this.deviceData.licensePlateNumber = this.name;
					}
					this.$store.commit("setDeviceData", this.deviceData);
					this.show = false;
					this.$showToast(`修改${label}成功`);
				})
			},
			//去认证
			gotoAuth(item) {
				this.$store.commit("setSpecialAppOnShow", true);
				if (item.isAuth == "1") {
					verifyCarAPI(item.id).then(([err, data]) => {
						if (err) return;
						let resData = JSON.parse(data);
						this.$store.commit("setVerifyUrl", resData.url)
						this.$reLaunch(`/pages/views/home/verify`)
					})
				}
			},
			numerRound(val) {
				let str = val + '';
				let lastNumber = parseInt(str.substring(str.length - 1));
				if (lastNumber < 5) {
					if (str.length > 1) {
						return parseInt(str.substring(0, str.length - 1) + "0");
					} else {
						return 0;
					}
				} else {
					if (str.length > 1) {
						return parseInt(str.substring(0, str.length - 1)) * 10 + 10;
					} else {
						return 10;
					}
				}
			},
			setNumerRound(val, arr, fix = 2) {
				let newval = this.toFormatVal(val, arr, fix);
				if (newval != '-') {
					return this.numerRound(newval);
				} else {
					return "-";
				}
			},
			toFormatVal(val, arr, fix = 2) {
				if (val == null || val === '') {
					return '-'
				}
				let n = getRangeVal(val, arr);
				return Number(n).toFixed(fix);
			},
			$value(value, decimals = -1, defaultStr = "-") {
				if (this.$validatenull(value)) {
					return defaultStr;
				} else {
					if (decimals == -1) {
						return value;
					} else {
						return Number(value).toFixed(decimals)
					}
				}
			}
		}
	}
</script>
